<template>
  <div class="chat-container">
    <!-- 导航栏 -->
    <NavBar title="消息">
      <template #right>
        <div class="nav-right">
          <van-icon name="search" :size="24" @click="handleSearch" />
          <van-icon name="add-o" :size="24" @click="showPopover = !showPopover" />
        </div>
        <!-- 下拉菜单 -->
        <van-popover
          v-model:show="showPopover"
          :actions="actions"
          :offset="[6, 20]"
          placement="bottom-end"
          @select="onSelect"
        >
          <template #actions>
            <div v-for="item in actions" :key="item.text" @click="onSelect(item)">
              <van-icon :name="item.icon" :size="22" />
              <span>{{ item.text }}</span>
            </div>
          </template>
        </van-popover>
      </template>
    </NavBar>
    <!-- 合并后的消息列表 -->
    <div class="message-list">
      <ChatList :messageList="messageList" v-if="messageList.length > 0" />
      <van-empty description="暂无消息" v-else />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { chatApi } from '@/api/chat'
import ChatList from './components/ChatList.vue'
import { chatService } from '@/utils/webSocket'

const router = useRouter()
const showPopover = ref(false)

// 下拉菜单选项
const actions = [
  {
    text: '添加朋友',
    icon: 'add-o',
  },
  {
    text: '发起群聊',
    icon: 'friends-o',
  },
  {
    text: '加入群聊',
    icon: 'friends-o',
  },
]

// 选择菜单项
const onSelect = (action) => {
  if (action.text === '发起群聊') {
    router.push('/chat/create')
  } else if (action.text === '添加朋友') {
    router.push('/chat/search')
  } else if (action.text === '加入群聊') {
    router.push('/chat/search')
  }
}

const chatList = ref([])
const roomList = ref([])

// 获取聊天列表
const getChatList = async () => {
  try {
    const res = await chatApi.getChatList()
    chatList.value = res
    console.log(chatList.value)
  } catch (error) {
    console.error(error)
  }
}

// 获取群聊列表
const getRoomList = async () => {
  try {
    const res = await chatApi.getRoomList()
    roomList.value = res
    console.log(roomList.value)
  } catch (error) {
    console.error(error)
  }
}

// 合并并处理消息列表
const messageList = computed(() => {
  const messages = []
  // 处理私聊消息
  if (chatList.value && chatList.value.length > 0) {
    chatList.value.forEach((item) => {
      if (item && item.lastMessage) {
        messages.push({
          id: item.id,
          avatar: item.avatar,
          name: item.name,
          type: 'private',
          lastMessage: {
            ...item.lastMessage,
            timestamp: new Date(item.lastMessage.timestamp),
          },
        })
      }
    })
  }

  // 处理群聊消息
  if (roomList.value && roomList.value.length > 0) {
    roomList.value.forEach((item) => {
      if (item) {
        messages.push({
          id: item.id,
          avatar: item.avatar,
          name: item.name,
          type: 'group',
          lastMessage: item.lastMessage
            ? {
                ...item.lastMessage,
                timestamp: new Date(item.lastMessage.timestamp),
              }
            : null,
          memberCount: item.memberCount,
        })
      }
    })
  }
  // return messages
  // 按最后消息时间排序
  return messages.sort((a, b) => {
    const timeA = new Date(a.lastMessage?.timestamp || 0).getTime()
    const timeB = new Date(b.lastMessage?.timestamp || 0).getTime()
    return timeB - timeA
  })
})

const handleSearch = () => {
  console.log('搜索')
}

onMounted(async () => {
  await Promise.all([getChatList(), getRoomList()])
  // 只在需要时连接 WebSocket
  if (!chatService.connected.value) {
    chatService.connect()
  }
})
</script>

<style scoped>
.chat-container {
  background-color: var(--bg-color);
  min-height: 100vh;
}
.nav-right {
  display: flex;
  gap: 16px;
  padding-right: 4px;
}

/* 下拉菜单样式 */
:deep(.van-popover__action:active) {
  background-color: transparent;
}

/* 添加图标悬停效果 */
.nav-right .van-icon {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.nav-right .van-icon:active {
  transform: scale(0.9);
}

.message-list {
  padding: var(--spacing-sm) 0;
}
</style>
